import 'package:city_pickers/city_pickers.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json2dart_safe/json2dart.dart';
import 'package:pornhub_app/components/ad_banner/ad_banner.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/community/city_model.dart';
import 'package:pornhub_app/model/community/province_list_model.dart';
import 'package:pornhub_app/model/community/province_model.dart';
import 'package:pornhub_app/model/engagement/engagement_model.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/views/engagement/views/lou_feng_cell.dart';

class LouFengListPage extends StatefulWidget {
  final String classifyId;

  const LouFengListPage({super.key, required this.classifyId});

  @override
  State<StatefulWidget> createState() => _LouFengListPageState();
}

class _LouFengListPageState extends State<LouFengListPage> {
  final refreshController = EasyRefreshController();
  late int _page = 1;
  late List<EngagementModel> _engagementList = [];
  var currentCity = '全国'.obs;

  Future<IndicatorResult> _initListData(int page, String cityName) async {
    final resp = await Api.getEngagementList(
      meetType: 2,
      classifyId: widget.classifyId,
      cityName: cityName,
      page: _page,
      pageSize: 10,
    );

    if (resp == null) {
      return IndicatorResult.fail;
    }

    setState(() {
      if (page == 1) {
        _engagementList.clear();
        _engagementList = resp;
      } else {
        _engagementList.addAll(resp);
      }
    });
    return IndicatorResult.success;
  }

  final us = Get.find<UserService>();

  ProvinceListModel get province => us.province;
  late List<ProvinceModel> _provinceList = [];
  late List<CityModel> cityList = [];
  Map<String, String> provincesData = {};
  Map<String, dynamic> citiesData = {};

  Future _initCityData() async {
    if (province.data != null) {
      _provinceList = province.data ?? [];
      if (_provinceList.isNotEmpty) {
        for (int i = 0; i < _provinceList.length; i++) {
          provincesData.put('${_provinceList[i].code}', _provinceList[i].name);
          if (_provinceList[i].cityList != null) {
            cityList = _provinceList[i].cityList ?? [];
            if (cityList.isNotEmpty) {
              Map<String, dynamic> citiesChildData = {};
              for (int j = 0; j < cityList.length; j++) {
                Map<String, String> citiesChildData02 = {};
                citiesChildData02.put('name', cityList[j].name);
                if (cityList[j].code == _provinceList[i].code) {
                  int code = int.tryParse('${cityList[j].code}') ?? 0;
                  citiesChildData.put('${(code + 100)}', citiesChildData02);
                } else {
                  citiesChildData.put('${cityList[j].code}', citiesChildData02);
                }
                citiesData.put('${_provinceList[i].code}', citiesChildData);
              }
            }
          }
        }
      }
    }
  }

  @override
  void initState() {
    _initCityData();
    _initListData(_page, currentCity.value);
    super.initState();
  }

  @override
  void dispose() {
    refreshController.dispose();
    super.dispose();
  }

  Widget _buildEngagementView() {
    return SliverList.builder(
        itemCount: _engagementList.isNotEmpty ? _engagementList.length : 1,
        itemBuilder: (context, index) {
          if (_engagementList.isNotEmpty) {
            return LouFengCell(
              data: _engagementList[index],
            );
          } else {
            return const NoData().marginOnly(top: 100.w);
          }
        });
  }

  Future _showDialog() {
    return showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.w),
          ),
          backgroundColor: Colors.white,
          child: SizedBox(
            height: 215.w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: <Widget>[
                    SizedBox(width: 118.w),
                    TextView(
                      text: '如何约妹',
                      color: COLOR.hexColor('#333333'),
                      fontSize: 16.w,
                      fontWeight: FontWeight.w500,
                    ),
                    SizedBox(width: 118.w),
                  ],
                ).paddingVertical(15.w),
                Divider(
                  color: COLOR.hexColor('#F0F0F0'),
                  height: 1.w,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    TextView(
                      text: '1.官方会整理并发布可与约会妹妹的信息资料',
                      color: COLOR.hexColor('#333333'),
                      fontSize: 12.w,
                      fontWeight: FontWeight.w400,
                    ).paddingTop(8.w),
                    TextView(
                      text: '2.服务范围覆盖全国一二三线城市',
                      color: COLOR.hexColor('#333333'),
                      fontSize: 12.w,
                      fontWeight: FontWeight.w400,
                    ).paddingTop(8.w),
                    TextView(
                      text: '3.点击解锁信息并支付相应金币，即可与MM畅快聊天并邀约MM',
                      color: COLOR.hexColor('#333333'),
                      fontSize: 12.w,
                      fontWeight: FontWeight.w400,
                    ).paddingTop(8.w),
                    TextView(
                      text: '4.如遇到解锁之后未能联系到MM，可联系官方客服说明情况',
                      color: COLOR.hexColor('#333333'),
                      fontSize: 12.w,
                      fontWeight: FontWeight.w400,
                    ).paddingTop(8.w),
                  ],
                ).paddingHorizontal(13.w).paddingTop(10.w),
              ],
            ),
          ),
        );
      },
    );
  }

  showCityPicker() async {
    Result? result = await CityPickers.showCityPicker(
      context: context,
      showType: ShowType.pc,
      cancelWidget: TextView(
        text: "取消",
        fontSize: 18.sp,
        color: COLOR.color_333333,
        fontWeight: FontWeight.w500,
      ),
      confirmWidget: TextView(
        text: "确定",
        fontSize: 18.sp,
        color: COLOR.color_333333,
        fontWeight: FontWeight.w500,
      ),
      citiesData: citiesData,
      provincesData: provincesData,
      height: 250.w,
      borderRadius: 10,
    );
    if (result != null) {
      currentCity.value = result.cityName ?? result.provinceName ?? "全国";
      _page = 1;
      _initListData(_page, currentCity.value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.builder(
      controller: refreshController,
      childBuilder: (context, physics) {
        return CustomScrollView(
          physics: physics,
          slivers: [
            SliverToBoxAdapter(
              child: const AdBanner(adress: AdPlaceNameEnum.NDD_BANNER)
                  .marginOnly(left: 14.w, top: 5.w, right: 14.w),
            ),
            SliverToBoxAdapter(
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            '如何约妹',
                            style: TextStyle(
                                color: COLOR.hexColor('#666666'),
                                fontSize: 16.w,
                                fontWeight: FontWeight.w500),
                          ),
                          SizedBox(width: 2.w),
                          Image.asset(
                            'assets/engagement/icon_engagement_question.png',
                            width: 15.w,
                            height: 15.w,
                          )
                        ],
                      ).onOpaqueTap(() {
                        _showDialog();
                      }),
                      Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset(
                              'assets/engagement/icon_city.png',
                              width: 15.w,
                              height: 15.w,
                            ),
                            SizedBox(width: 5.w),
                            Obx(
                              () => Text(
                                currentCity.value,
                                style: TextStyle(
                                    color: COLOR.hexColor('#DD001B'),
                                    fontSize: 14.w,
                                    fontWeight: FontWeight.w400),
                              ),
                            ),
                            Icon(
                              Icons.chevron_right,
                              color: COLOR.hexColor('#DD001B'),
                            ),
                          ]).onOpaqueTap(() {
                        showCityPicker();
                      }),
                    ],
                  ),
                  SizedBox(height: 12.w),
                ],
              ).marginOnly(left: 14.w, right: 14.w, top: 20.w),
            ),
            _buildEngagementView(),
          ],
        );
      },
      onRefresh: () async {
        _page = 1;
        return _initListData(_page, currentCity.value);
      },
      onLoad: () async {
        _page++;
        return _initListData(_page, currentCity.value);
      },
    );
  }
}
